<template>
  <div>
    <div class="search-list mb-10">
      <el-date-picker type="date"
                      placeholder="选择日期"
                      v-model="searchForm.time"
                      :picker-options="pickerOptions1"
                      format="yyyy-MM-dd"
                      size="small"
                      class="mr-10"
                      value-format="yyyy-MM-dd"></el-date-picker>
      <el-button type="primary" size="small" @click="searchFn('search')" class="ml-10"><i class="el-icon-search"></i>搜索
      </el-button>
      <el-button size="small" @click="searchFn('refresh')"><i class="el-icon-refresh"></i>重置刷新</el-button>
    </div>
    <div class="user-content">
      <div class="user-list-train" v-for="item in teacherTrain" :key="item.id" @click="openListFn(item)">
        <div>
          <ImagePreview :src="item.pic" width="60px"
                        height="60px" :previewStatus="false"></ImagePreview>
        </div>
        <p class="user-list-name">{{item.realname}}</p>
        <div class="user-list-name">
<!--          <span>今日巡班</span>-->
<!--          <span>{{trainDay[item.id]?trainDay[item.id].length:0}}</span>-->
          <span>{{`${item.day}/${item.month}/${item.semester}`}}</span>
        </div>
      </div>
    </div>
    <el-tabs v-model="searchForm.department_id" type="card">
      <el-tab-pane :label="item.name" :name="item.id" v-for="item in tabDepartment" :key="item.id"></el-tab-pane>
    </el-tabs>
    <el-tabs v-model="areaType" type="card">
      <el-tab-pane :label="item.name" :name="item.id" v-for="item in userListOoption" :key="item.id"></el-tab-pane>
    </el-tabs>
    <div class="table-line-body mt-10 yangTable">
      <el-table
          :data="tablist"
          row-key="id"
          :default-expand-all="isExpandAll"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column prop="name" label="巡班项" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="name" align="center" width="120" label="巡班类型" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span v-if="scope.row.parent_id">
              {{typelistOption[scope.row.type]}}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="name" width="120" align="center" label="巡班对象" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span v-if="scope.row.parent_id">{{
                userList[scope.row.user_type] ? userList[scope.row.user_type].name : ''
              }}</span>
          </template>
        </el-table-column>
        <el-table-column label="巡班详情" align="center" class-name="small-padding fixed-width" width="80">
          <template slot-scope="scope">
            <el-popover
                placement="left-start"
                title="当日巡班明细"
                width="550"
                v-if="scope.row.parent_id && listData[scope.row.id] && listData[scope.row.id][areaType]"
                trigger="hover">
              <div class="popover-table">
                <div class="popover-list">
                  <div class="popover-title">
                    <span>班级</span>
                    <span>巡班人</span>
                    <span>分值</span>
                    <span>巡班意见</span>
                    <span>巡班时间</span>
                  </div>
                  <div class="popover-body">
                    <div class="popover-list-line" v-for="(item,index) in listData[scope.row.id][areaType]"
                         :key="index">
                      <span>{{ item.class_name }}</span>
                      <span>{{ item.user_name }}</span>
                      <span>{{ item.score }}星</span>
                      <span>{{ item.remark }}</span>
                      <span>{{ item.time }}</span>
                    </div>
                  </div>
                </div>
              </div>
              <span slot="reference" class="tablelineBtn">{{
                  listData[scope.row.id] && listData[scope.row.id][areaType] ? listData[scope.row.id][areaType].length : 0
                }}条</span>
            </el-popover>
            <el-link v-if="scope.row.parent_id && !listData[scope.row.id]" type="danger" :underline="false">未评价</el-link>
            <el-link v-if="!scope.row.parent_id && showAllCateFn(scope.row.children)==='未评价'" type="danger" :underline="false">未评价</el-link>
            <el-link v-if="!scope.row.parent_id && showAllCateFn(scope.row.children)!=='未评价'" type="primary" :underline="false">{{showAllCateFn(scope.row.children)}}条</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="height40"></div>
    <userTrainingDay :visible.sync="trainVisible" :trainList="trainList" :showTeacherOption="showTeacherOption" :dayTime="searchForm.time"></userTrainingDay>
  </div>
</template>

<script>
import {pagination} from '@/utils/util.js'
import {classDynamiceIndex, classDynamiceDelete, statisticsPatrol} from "@/api/admin/ClassDynamics"
import userTrainingDay from './userTrainingDay'
export default {
  components: {userTrainingDay},
  data() {
    return {
      trainVisible: false,
      trainList: [],
      tableStripe: true, // 是否斑马栏
      tableBorder: true, // 单元格右边边框
      arryList: [], // 数据列表
      patrolVisible: false,
      // 页数
      page: {
        pageindex: pagination.pageIndex,
        pagesize: pagination.pageSize,
        total: pagination.total
      },
      checkTab: '',
      optionData: null,
      searchBox: {
        class_id: '',
        section_id: ''
      },
      searchForm: {
        time: '',
        class_id: '',
        section_id: '',
        department_id: '1',
      },
      tabDepartment: [
        {
          name: '行政',
          id: '1'
        },
        {
          name: '后勤',
          id: '2',
        },
        {
          name: '业务',
          id: '3',
        }
      ],
      userList: {
        1: {
          name: '幼儿',
          id: 1
        },
        2: {
          name: '教师',
          id: 2
        },
        4: {
          name: '生活老师',
          id: 4
        },
        3: {
          name: '场地',
          id: 3
        }
      },
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() > Date.now() //  - 8.64e7
        }
      },
      typelistOption: {
        1: '班级',
        2: '公共区域',
        3: '通用'
      },
      areaType: '1',
      userListOoption: [
        {
          name: '幼儿',
          id: '1'
        },
        {
          name: '教师',
          id: '2'
        },
        {
          name: '生活老师',
          id: '4'
        },
        {
          name: '场地',
          id: '3'
        }
      ],
      optionType: '',
      treeList: [],
      isExpandAll: false,
      selectList: [],
      listData: {},
      tablist: [],
      teacherTrain: [], // 巡班老师
      trainDay: {}, // 今日巡班老师记录
      Weekdate: '--',
      Weektime: '--',
      weekName: '--',
      showTeacherOption: null
    }
  },
  watch: {
    'searchForm.department_id'() {
      console.log('变了tabs')
      this.listData = {}
      this.InitFn()
      this.InitTableListFn()
    },
    areaType() {
      this.tablist = []
      this.checkTableList()
    }
  },
  created() {
    this.InitFn()
    this.InitTableListFn()
    // this.teacherFn()
    this.updateTime()
    this.statisticsPatrolFn()
  },
  methods: {
    updateTime() {
      let cd = new Date()
      this.Weektime = this.zeroPadding(cd.getHours(), 2) + ':' + this.zeroPadding(cd.getMinutes(), 2) + ':' + this.zeroPadding(cd.getSeconds(), 2)
      this.Weekdate = this.zeroPadding(cd.getFullYear(), 4) + '-' + this.zeroPadding(cd.getMonth() + 1, 2) + '-' + this.zeroPadding(cd.getDate(), 2)
      // this.weekName = this.week[cd.getDay()]
      this.searchForm.time = this.Weekdate;
    },
    zeroPadding(num, digit) {
      let zero = ''
      for (let i = 0; i < digit; i++) {
        zero += '0'
      }
      return (zero + num).slice(-digit)
    },
    showAllCateFn(list){
      let num_ = 0
      for(let item of list){
        if(this.listData[item.id] && this.listData[item.id][this.areaType]){
          num_ = num_ + this.listData[item.id][this.areaType].length
        }
      }
      if(!num_){
        return '未评价'
      }else{
        return num_
      }
    },
    // 搜索组件
    searchFn(option) {
      if (option === 'refresh') {
        this.searchForm.time = this.Weekdate;
        this.searchForm.class_id = '';
        this.searchForm.section_id = '';
        this.searchForm.department_id = '1';
      }else{
        if(!this.searchForm.time){
          this.searchForm.time = this.Weekdate;
        }
      }
      this.InitFn()
      this.InitTableListFn()
      // this.teacherFn()
      this.statisticsPatrolFn()
    },
    openListFn(item){
      if(this.trainDay[item.id]){
        this.trainList = JSON.parse(JSON.stringify(this.trainDay[item.id]))
      }else{
        this.trainList = []
      }
      this.showTeacherOption = JSON.parse(JSON.stringify(item))
      // else{
      //   this.$message.error('今日未巡班')
      // }
      this.trainVisible = true
    },
    // 获取巡班老师
    async teacherFn() {
      let data = await this.$fetch(this.api.classActive.training.index, {p: 0})
      let list_ = []
      let user_list = []
      for(let item of data.list){
        if(item.user_ids){
          for(let user_ of item.user_ids){
            if(list_.indexOf(user_.id)===-1){
              list_.push(user_.id)
              user_list.push(user_)
            }
          }
        }
      }
      this.teacherTrain = JSON.parse(JSON.stringify(user_list))
    },
    // 初始化
    InitTableListFn() {
      // let data_ = JSON.parse(JSON.stringify(this.searchForm))
      this.$fetch(this.api.classActive.trainHistory.index, {time: this.searchForm.time,class_id: '', section_id: '', department_id: ''}).then((response) => {
        if (!response.code) {
          let list_ = {}
          let tearcher_ = {}
          for (let item of response.list) {
            // 班级
            for (let children of item.list) {
              // 每个老师巡班
              let line_ = {
                class_name: item.class_name,
                class_id: item.class_id,
                list: children.list,
                user_type: children.user_type,
                time: children.time,
                score: 0,
                remark: children.remark
              }
              let num_ = 0
              for (let line of children.list) {
                // 巡班细项
                let item_ = JSON.parse(JSON.stringify(line))
                item_.class_name = item.class_name
                item_.user_name = children.realname
                item_.remark = children.remark
                num_ = num_ + line.score
                if (children.time) {
                  let time_ = children.time.split(' ')
                  let a_ = time_[1].split(":")
                  a_.splice(2, 1)
                  time_[1] = a_.join(':')
                  item_.time = time_.join(' ')
                } else {
                  item_.time = ''
                }

                if (list_[line.id]) {
                  if (list_[line.id][children.user_type]) {
                    list_[line.id][children.user_type].push(item_)
                  } else {
                    list_[line.id][children.user_type] = [item_]
                  }
                } else {
                  list_[line.id] = {}
                  list_[line.id][children.user_type] = [item_]
                }
              }
              line_.score = num_
              if (!tearcher_[children.id]) {
                tearcher_[children.id] = [line_]
              } else {
                tearcher_[children.id].push(line_)
              }
            }
          }
          console.log('tearcher_:', tearcher_)
          this.trainDay = JSON.parse(JSON.stringify(tearcher_))
          console.log('重组后的数据的数据内容：', list_)
          this.listData = JSON.parse(JSON.stringify(list_))
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 初始化
    async InitFn() {
      let option_ = JSON.parse(JSON.stringify(this.searchBox))
      option_.p = 0
      option_.department_id = this.searchForm.department_id
      classDynamiceIndex(option_).then(res => {
        if (!res.code) {
          this.treeList = this.$handleTree(res.list, 'id', 'parent_id');
          let list = this.$handleTree(res.list, 'id', 'parent_id')
          list.unshift({id: 0, name: '主类目'}) // dataMenu.data
          this.selectList = list
          this.page.total = res.list.total;
          this.checkTableList()
        }
      })
    },
    checkTableList() {
      let list_ = JSON.parse(JSON.stringify(this.treeList))
      let newList = []
      for (let item of list_) {
        let children_list = []
        if (item.children) {
          for (let children of item.children) {
            if (Number(this.areaType) === children.user_type) {
              children_list.push(children)
            }
          }
        }
        item.children = children_list
        if(item.children.length){
          newList.push(item)
        }
      }
      this.tablist = JSON.parse(JSON.stringify(newList))
    },
    // 分页
    handleSizeChange(val) {
      this.page.pageindex = val
      this.InitFn()
    },
    handleSelectionChange(val) {
      this.handleSelection = val
    },
    deletefn(row) {
      this.$confirm(`确认删除【${row.name}】, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.detelRespon(row.id)
      }).catch(() => {
      })
    },
    async detelRespon(id) {
      classDynamiceDelete({id: id}).then(res => {
        if (!res.code) {
          this.$message.success(res.msg)
          this.InitFn()
        }
      })
    },
    editCate(type, row) {
      this.optionType = type
      this.optionData = row
      this.patrolVisible = true
    },
    statisticsPatrolFn(){
      statisticsPatrol().then(res=>{
        this.teacherTrain = res.list
      })
    }
  },
  mounted() {
  },
}
</script>
<style>
.lead-list {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fddeae;
  margin-bottom: 5px;
  border-radius: 2px;
  padding: 5px 0;
}

.lead-list:last-child {
  margin-bottom: 0;
}

.lead-list span {
  margin-right: 30px;
}

.popover-table {
  max-height: 300px;
  min-height: 200px;
}

.popover-list {
  display: flex;
  flex-direction: column;
  height: 250px;
  cursor: pointer;
}

.popover-title {
  height: 30px;
  line-height: 30px;
  background: #eee;
  display: flex;
}

.popover-title span {
  text-align: center;
  display: block;
}

.popover-title span:first-child {
  width: 90px;
}

.popover-title span:nth-child(2) {
  flex: 1;
}

.popover-title span:nth-child(4) {
  flex: 1;
}

.popover-title span:nth-child(5) {
  flex: 1;
}

.popover-title span:nth-child(3) {
  width: 80px;
}

.popover-body {
  flex: 1;
  overflow-y: auto;
}

.popover-list-line {
  display: flex;
  border-bottom: 1px solid #ddd;
  /*height: 30px;*/
  /*line-height: 30px;*/
  align-items: center;
  padding: 5px 0;
}

.popover-list-line span {
  display: block;
  text-align: center;
}

.popover-list-line span:first-child {
  width: 90px;
}

.popover-list-line span:nth-child(2) {
  flex: 1;
}

.popover-list-line span:nth-child(3) {
  width: 80px;
  color: red;
}

.popover-list-line span:nth-child(4) {
  flex: 1;
}

.popover-list-line span:nth-child(5) {
  flex: 1;
}

.user-content {
  overflow: hidden;
  padding: 10px 0;
}

.user-list-train {
  display: flex;
  align-items: center;
  flex-direction: column;
  border: 1px solid #ddd;
  border-radius: 5px;
  float: left;
  padding: 10px;
  margin-right: 10px;
  cursor: pointer;
  margin-bottom: 10px;
}

.user-list-train:hover {
  box-shadow: 0 2px 3px #ff8815;
}

.user-list-name {
  display: flex;
  align-items: center;
  width: 85px;
  justify-content: center;
}

/*.user-list-name span:first-child {*/
/*  color: #999;*/
/*  padding-right: 10px;*/
/*  font-size: 12px;*/
/*}*/

.user-list-name span{
  color: #ea2d00;
  font-weight: 500;
  font-size: 16px;
}
</style>
<!--<div class="user-content">-->
<!--<div class="user-list">-->
<!--  <div>-->
<!--    <ImagePreview src="/uploads/20220217/6239d5660806bccd2bcff0f1bb2fc08e_250_250.png" width="40px" height="40px"></ImagePreview>-->
<!--  </div>-->
<!--  <p class="user-list-name">王宇清</p>-->
<!--  <div class="user-list-name">-->
<!--    <span>今日巡班</span>-->
<!--    <span>3</span>-->
<!--  </div>-->
<!--</div>-->
<!--</div>-->
